package com.cloudfun.campusshare.service.handler;

import com.cloudfun.campusshare.common.constant.DelayMsgType;
import com.cloudfun.campusshare.device.protocol.AliyunIotService;
import com.cloudfun.campusshare.device.protocol.handler.AliyunIotDeviceStatusHandler;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.sender.DelayMessage;
import com.cloudfun.campusshare.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Huqin on 2020/6/24
 */
@Slf4j
@Component
public class AliyunDeviceStatusRegulateHandler implements DelayMessageHandler {

    @Autowired
    private AliyunIotDeviceStatusHandler aliyunIotDeviceStatusHandler;

    @Autowired
    private AliyunIotService aliyunIotService;

    @Autowired
    private DeviceService deviceService;

    @Override
    public DelayMsgType support() {
        return DelayMsgType.ALIYUN_DEVICE_STATUS_REGULATE;
    }

    @Override
    public void handleMessage(DelayMessage message) {
        String deviceImei = message.getDeviceId();
        DeviceEntity device = deviceService.getDeviceWithoutAuthByImei(deviceImei);
        String deviceStatus = aliyunIotService.getDeviceStatus(device.getAliyunProdKey(), deviceImei);
        boolean online = StringUtils.equals(AliyunIotDeviceStatusHandler.ONLINE_FLAG.toUpperCase(), deviceStatus);
        log.info("从阿里云查询到设备：{}的状态为：{}，{}", deviceImei, deviceStatus, online);
        if (!device.getOnline().equals(online)) {
            aliyunIotDeviceStatusHandler.handleStatusChange(online, deviceImei, device.getAliyunProdKey(), System.currentTimeMillis() + "");
        }
    }
}
